package org.glow.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.glow.changgou.goods.dao.SpuMapper;
import org.glow.changgou.goods.pojo.*;
import org.glow.changgou.goods.service.BrandService;
import org.glow.changgou.goods.service.CategoryService;
import org.glow.changgou.goods.service.SkuService;
import org.glow.changgou.goods.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.glow.changgou.entity.IdWorker;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author Glow
 * @Date 2022-09-24 14:06:46
 * @Description
 * @Version 1.0
 */
@Service
public class SpuServiceImpl extends ServiceImpl<SpuMapper, Spu> implements SpuService {
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private  SpuService spuService;
    @Resource
    private SpuMapper spuMapper;
    @Override
    public Page<Spu> findPage(Spu spu, int page, int size) {
        Page<Spu> pageInfo = new Page<>(page,size);
        LambdaQueryWrapper<Spu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = getCondition(queryWrapper,spu);
        //执行搜索
        return spuService.page(pageInfo,queryWrapper);
    }

    @Override
    public Page<Spu> findPage(int page, int size) {
        Page<Spu> pageInfo = new Page<>(page,size);
        return spuService.page(pageInfo);
    }

    @Override
    public List<Spu> findList(Spu spu) {
        //构建查询条件
        LambdaQueryWrapper<Spu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper = getCondition(queryWrapper,spu);
        //根据构建的条件查询数据
        return spuService.list(queryWrapper);
    }

    @Override
    public void delete(Long id) {
        Spu spu = spuService.getById(id);
        if(spu.getIsDelete().equals("0"))
        {
            throw  new RuntimeException("该商品未被逻辑删除");
        }
            spuService.removeById(id);
    }



    @Override
    public void add(Spu spu) {
            spuService.add(spu);
    }

    @Override
    public Spu findById(Long id) {
        return spuService.getById(id);
    }

    @Override
    public List<Spu> findAll() {
        return spuService.list();
    }

    @Override
    public void save(Goods goods) {

    }

    @Override
    public Goods findGoodsById(Long id) {
        //查询Spu
        Spu spu = spuService.getById(id);

        //查询List<Sku>

        List<Sku> skus = skuService.list(new LambdaQueryWrapper<Sku>().eq(Sku::getSpuId,id));
        System.out.println(skus.toString());
        //封装Goods
        Goods goods = new Goods();
        goods.setSkuList(skus);
        goods.setSpu(spu);
        return goods;
    }

    @Override
    public void auditSpu(Long id) {

    }

    @Override
    public void pullSpu(Long id) {

    }

    @Override
    public void logicDeleteSpu(Long id) {
            Spu spu = spuService.getById(id);
            if(spu.getIsMarketable().equals("1"))
            {
                throw new RuntimeException("请先讲商品下架！");
            }
            spu.setIsDelete("1");
            spu.setStatus("0");
            spuService.updateById(spu);
    }

    @Override
    public void restoreSpu(Long id) {
            Spu spu = spuService.getById(id);
            if(spu.getIsDelete().equals("0"))
            {
                throw  new RuntimeException("该商品未被删除");
            }
            spu.setIsDelete("0");
            spu.setStatus("0");
            spuService.updateById(spu);
    }
    @Transactional
    @Override
    public void saveGoods(Goods goods) {
        //增加Spu
        Spu spu = goods.getSpu();
        if(spu.getId() == null)
        {
            spu.setId(idWorker.nextId());
            spuService.save(spu);
        }else {
            spuService.updateById(spu);
            Sku sku = new Sku();
            sku.setSpuId(spu.getId());
            skuService.removeById(sku);
        }


        //增加Sku
        Date date = new Date();
        Category category = categoryService.getById(spu.getCategory3Id());
        Brand brand = brandService.getById(spu.getBrandId());
        //获取Sku集合
        List<Sku> skus = goods.getSkuList();
        //循环将数据加入到数据库
        for (Sku sku : skus) {
            //构建SKU名称，采用SPU+规格值组装
            if(StringUtils.isEmpty(sku.getSpec())){
                sku.setSpec("{}");
            }
            //获取Spu的名字
            String name = spu.getName();

            //将规格转换成Map
            Map<String,String> specMap = JSON.parseObject(sku.getSpec(), Map.class);
            //循环组装Sku的名字
            for (Map.Entry<String, String> entry : specMap.entrySet()) {
                name+="  "+entry.getValue();
            }
            sku.setName(name);
            //ID
            sku.setId(idWorker.nextId());
            //SpuId
            sku.setSpuId(spu.getId());
            //创建日期
            sku.setCreateTime(date);
            //修改日期
            sku.setUpdateTime(date);
            //商品分类ID
            sku.setCategoryId(spu.getCategory3Id());
            //分类名字
            sku.setCategoryName(category.getName());
            //品牌名字
            sku.setBrandName(brand.getName());
            //增加
            skuService.save(sku);
        }
    }

    /**
     * 修改sku库存
     * @param goods
     */
    @Override
    public void updateGoodsSku(Goods goods) {
        List<Sku> list = goods.getSkuList();
        skuService.updateBatchById(list);
    }

    /***
     * 商品审核
     * @param spuId
     */
    @Override
    public void audit(Long spuId) {
        //查询商品
        Spu spu = spuService.getById(spuId);
        //判断商品是否已经删除
        if(spu.getIsDelete().equalsIgnoreCase("1")){
            throw new RuntimeException("该商品已经删除！");
        }
        //实现上架和审核
        spu.setStatus("1"); //审核通过
        spu.setIsMarketable("1"); //上架
        spuService.updateById(spu);
    }

    /**
     * 商品下架
     * @param spuId
     */
    @Override
    public void pull(Long spuId) {
        Spu spu = spuService.getById(spuId);
        if(spu.getIsDelete().equals("1")){
            throw new RuntimeException("此商品已删除！");
        }
//        spu.setStatus("0");
        spu.setIsMarketable("0");//下架状态
        LambdaUpdateWrapper<Spu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Spu::getId,spuId);
        spuService.update(spu,updateWrapper);
    }

    /***
     * 商品上架
     * @param spuId
     */
    @Override
    public void put(Long spuId) {
        Spu spu = spuService.getById(spuId);
        //检查是否删除的商品
        if(spu.getIsDelete().equals("1")){
            throw new RuntimeException("此商品已删除！");
        }
        if(!spu.getStatus().equals("1")){
            throw new RuntimeException("未通过审核的商品不能！");
        }
        //上架状态
        spu.setIsMarketable("1");
        spuService.updateById(spu);
    }

    /***
     * 批量上架
     * @param ids:需要上架的商品ID集合
     * @return
     */
    @Transactional
    @Override
    public int putMany(Long[] ids) {
        Spu spu=new Spu();
        spu.setIsMarketable("1");//上架
        //批量修改
        LambdaUpdateWrapper<Spu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Spu::getId, Arrays.asList(ids));
        //下架
        updateWrapper.eq(Spu::getIsMarketable,0);
//        criteria.andEqualTo("isMarketable","0");
        //审核通过的
//        criteria.andEqualTo("status","1");
        updateWrapper.eq(Spu::getStatus,1);
        //非删除的
//        criteria.andEqualTo("isDelete","0");
        updateWrapper.eq(Spu::getIsDelete,0);
        return spuMapper.update(spu, updateWrapper);
    }
    @Transactional
    @Override
    public int pullMany(Long[] ids) {
        Spu spu=new Spu();
        spu.setIsMarketable("0");//下架
        spu.setStatus("0");//下架需要重新审核哦
        //批量修改
        LambdaUpdateWrapper<Spu> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(Spu::getId, Arrays.asList(ids));
        //下架
        updateWrapper.eq(Spu::getIsMarketable,1);
//        criteria.andEqualTo("isMarketable","0");
        //审核通过的
//        criteria.andEqualTo("status","1");
        updateWrapper.eq(Spu::getStatus,1);
        //非删除的
//        criteria.andEqualTo("isDelete","0");
        updateWrapper.eq(Spu::getIsDelete,0);
        return spuMapper.update(spu, updateWrapper);
    }


    public LambdaQueryWrapper<Spu> getCondition(LambdaQueryWrapper<Spu> queryWrapper, Spu spu){
        queryWrapper.eq(Spu::getIsDelete,0);

        if (spu != null) {
            // 主键
            if (!StringUtils.isEmpty(spu.getId())) {
//                criteria.andEqualTo("id", spu.getId());
                queryWrapper.eq(Spu::getId,spu.getId());
            }
            // 货号
            if (!StringUtils.isEmpty(spu.getSn())) {
//                criteria.andEqualTo("sn", spu.getSn());
                queryWrapper.eq(Spu::getSn,spu.getSn());
            }
            // SPU名
            if (!StringUtils.isEmpty(spu.getName())) {
//                criteria.andLike("name", "%" + spu.getName() + "%");
                queryWrapper.like(Spu::getName,spu.getName());
            }
            // 副标题
            if (!StringUtils.isEmpty(spu.getCaption())) {
//                criteria.andEqualTo("caption", spu.getCaption());
                queryWrapper.eq(Spu::getCaption,spu.getCaption());
            }
            // 品牌ID
            if (!StringUtils.isEmpty(spu.getBrandId())) {
//                criteria.andEqualTo("brandId", spu.getBrandId());
                queryWrapper.eq(Spu::getBrandId,spu.getBrandId());
            }
            // 一级分类
            if (!StringUtils.isEmpty(spu.getCategory1Id())) {
//                criteria.andEqualTo("category1Id", spu.getCategory1Id());
                queryWrapper.eq(Spu::getCategory1Id,spu.getCategory1Id());
            }
            // 二级分类
            if (!StringUtils.isEmpty(spu.getCategory2Id())) {
//                criteria.andEqualTo("category2Id", spu.getCategory2Id());
                queryWrapper.eq(Spu::getCategory2Id,spu.getCategory2Id());
            }
            // 三级分类
            if (!StringUtils.isEmpty(spu.getCategory3Id())) {
//                criteria.andEqualTo("category3Id", spu.getCategory3Id());
                queryWrapper.eq(Spu::getCategory3Id,spu.getCategory3Id());
            }
            // 模板ID
            if (!StringUtils.isEmpty(spu.getTemplateId())) {
//                criteria.andEqualTo("templateId", spu.getTemplateId());
                queryWrapper.eq(Spu::getTemplateId,spu.getTemplateId());
            }
            // 运费模板id
            if (!StringUtils.isEmpty(spu.getFreightId())) {
//                criteria.andEqualTo("freightId", spu.getFreightId());
                queryWrapper.eq(Spu::getFreightId,spu.getFreightId());
            }
            // 图片
            if (!StringUtils.isEmpty(spu.getImage())) {
//                criteria.andEqualTo("image", spu.getImage());
                queryWrapper.eq(Spu::getImage,spu.getImage());
            }
            // 图片列表
            if (!StringUtils.isEmpty(spu.getImages())) {
//                criteria.andEqualTo("images", spu.getImages());
                queryWrapper.eq(Spu::getImages,spu.getImages());
            }
            // 售后服务
            if (!StringUtils.isEmpty(spu.getSaleService())) {
//                criteria.andEqualTo("saleService", spu.getSaleService());
                queryWrapper.eq(Spu::getSaleService,spu.getSaleService());
            }
            // 介绍
            if (!StringUtils.isEmpty(spu.getIntroduction())) {
//                criteria.andEqualTo("introduction", spu.getIntroduction());
                queryWrapper.eq(Spu::getIntroduction,spu.getIntroduction());
            }
            // 规格列表
            if (!StringUtils.isEmpty(spu.getSpecItems())) {
//                criteria.andEqualTo("specItems", spu.getSpecItems());
                queryWrapper.eq(Spu::getSpecItems,spu.getSpecItems());
            }
            // 参数列表
            if (!StringUtils.isEmpty(spu.getParaItems())) {
//                criteria.andEqualTo("paraItems", spu.getParaItems());
                queryWrapper.eq(Spu::getParaItems,spu.getParaItems());
            }
            // 销量
            if (!StringUtils.isEmpty(spu.getSaleNum())) {
//                criteria.andEqualTo("saleNum", spu.getSaleNum());
                queryWrapper.eq(Spu::getSaleNum,spu.getSaleNum());
            }
            // 评论数
            if (!StringUtils.isEmpty(spu.getCommentNum())) {
//                criteria.andEqualTo("commentNum", spu.getCommentNum());
                queryWrapper.eq(Spu::getCommentNum,spu.getCommentNum());
            }
            // 是否上架
            if (!StringUtils.isEmpty(spu.getIsMarketable())) {
//                criteria.andEqualTo("isMarketable", spu.getIsMarketable());
                queryWrapper.eq(Spu::getIsMarketable,spu.getIsMarketable());
            }
            // 是否启用规格
            if (!StringUtils.isEmpty(spu.getIsEnableSpec())) {
//                criteria.andEqualTo("isEnableSpec", spu.getIsEnableSpec());
                queryWrapper.eq(Spu::getIsEnableSpec,spu.getIsEnableSpec());
            }
            // 是否删除
            if (!StringUtils.isEmpty(spu.getIsDelete())) {
//                criteria.andEqualTo("isDelete", spu.getIsDelete());
                queryWrapper.eq(Spu::getIsDelete,spu.getIsDelete());
            }
            // 审核状态
            if (!StringUtils.isEmpty(spu.getStatus())) {
//                criteria.andEqualTo("status", spu.getStatus());
                queryWrapper.eq(Spu::getStatus,spu.getStatus());
            }
        }
        return queryWrapper;
    }

}
